import { ref } from 'vue'
import type {
  PaymentInfo,
  PaymentMethod,
  PaymentStatus,
  BalancePaymentInput,
  QrPaymentData,
  PaymentConfig,
} from '../types/payment'

// 默认支付配置
const defaultConfig: PaymentConfig = {
  qrTimeout: 300, // 5分钟
  pollInterval: 5000, // 5秒
}

class PaymentService {
  // 当前支付信息
  private currentPayment = ref<PaymentInfo | null>(null)

  // 支付配置
  private config: PaymentConfig = defaultConfig

  // 支付结果订阅回调
  private callbacks: Map<string, (payment: PaymentInfo) => void> = new Map()

  // 设置配置
  setConfig(config: Partial<PaymentConfig>) {
    this.config = { ...defaultConfig, ...config }
  }

  // 创建支付
  async createPayment(
    orderId: string,
    amount: number,
    method: PaymentMethod,
  ): Promise<PaymentInfo> {
    // 模拟创建支付
    const payment: PaymentInfo = {
      id: `pay_${Date.now()}`,
      orderId,
      orderNumber: `ORD${Date.now().toString().slice(5)}`,
      amount,
      method,
      status: 'pending',
      createTime: new Date(),
    }

    this.currentPayment.value = payment

    // 根据支付方式初始化支付
    if (method === 'wechat') {
      // 模拟微信支付初始化
      this.mockWechatPayment()
    } else if (method === 'qr') {
      // 初始化二维码支付
      this.initQrPayment()
    }

    return payment
  }

  // 模拟微信支付
  private mockWechatPayment() {
    if (!this.currentPayment.value) return

    // 模拟支付处理时间(3-10秒)
    const processTime = 3000 + Math.random() * 7000

    // 模拟支付成功/失败(80%成功)
    const success = Math.random() > 0.2

    setTimeout(() => {
      if (!this.currentPayment.value) return

      if (success) {
        this.updatePaymentStatus('success')
      } else {
        this.updatePaymentStatus('failed')
      }
    }, processTime)
  }

  // 余额支付
  async payWithBalance(input: BalancePaymentInput): Promise<PaymentStatus> {
    if (!this.currentPayment.value) return 'failed'

    // 模拟API请求
    return new Promise((resolve) => {
      // 模拟验证时间
      setTimeout(() => {
        // 模拟验证逻辑
        const validPassword = input.password === '123456' // 实际项目中应使用加密传输
        const sufficientBalance = input.amount <= 5000 // 模拟用户余额

        if (validPassword && sufficientBalance) {
          this.updatePaymentStatus('success')
          resolve('success')
        } else if (!validPassword) {
          resolve('failed') // 密码错误
        } else {
          resolve('failed') // 余额不足
        }
      }, 1500)
    })
  }

  // 初始化二维码支付
  private initQrPayment() {
    if (!this.currentPayment.value) return

    // 生成二维码内容
    const qrContent = `payment://${this.currentPayment.value.id}?amount=${this.currentPayment.value.amount}`

    // 设置支付数据到状态
    ;(this.currentPayment.value as any).qrData = {
      qrCode: `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${qrContent}`,
      expiresAt: Date.now() + this.config.qrTimeout * 1000,
    }

    // 启动轮询
    this.pollPaymentStatus()
  }

  // 轮询支付状态
  pollPaymentStatus() {
    const paymentId = this.currentPayment.value?.id
    if (!paymentId) return

    const intervalId = setInterval(async () => {
      if (!this.currentPayment.value) {
        clearInterval(intervalId)
        return
      }

      // 模拟API请求获取支付状态
      const status = await this.mockCheckPaymentStatus(paymentId)
      if (status !== 'pending' && status !== 'processing') {
        clearInterval(intervalId)

        if (status === 'success') {
          this.updatePaymentStatus('success')
        } else {
          this.updatePaymentStatus('failed')
        }
      } else if (this.currentPayment.value.method === 'qr') {
        // 检查二维码是否过期
        const qrData = (this.currentPayment.value as any).qrData as QrPaymentData
        if (qrData && qrData.expiresAt < Date.now()) {
          clearInterval(intervalId)
          this.updatePaymentStatus('failed')
        }
      }
    }, this.config.pollInterval)
  }

  // 模拟检查支付状态
  private async mockCheckPaymentStatus(paymentId: string): Promise<PaymentStatus> {
    // 模拟API延迟
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 模拟支付状态变化
    if (!this.currentPayment.value) return 'failed'

    // 根据时间推移模拟成功概率
    const elapsed = Date.now() - this.currentPayment.value.createTime.getTime()
    if (elapsed > 15000) {
      // 超过15秒 50%概率超时失败
      return Math.random() > 0.5 ? 'success' : 'failed'
    }

    if (elapsed > 10000) {
      // 10-15秒 80%概率支付成功
      return Math.random() > 0.2 ? 'success' : 'processing'
    }

    return Math.random() > 0.7 ? 'success' : 'processing'
  }

  // 更新支付状态
  private updatePaymentStatus(status: PaymentStatus) {
    if (!this.currentPayment.value) return

    const updatedPayment = {
      ...this.currentPayment.value,
      status,
      completeTime: status !== 'pending' && status !== 'processing' ? new Date() : undefined,
    }

    this.currentPayment.value = updatedPayment

    // 触发回调
    this.callbacks.forEach((callback) => callback(updatedPayment))

    // 支付完成后的处理
    if (status !== 'pending' && status !== 'processing') {
      console.log(`Payment ${status}: ${updatedPayment.id}`)

      // 30秒后清除当前支付
      setTimeout(() => {
        if (this.currentPayment.value?.id === updatedPayment.id) {
          this.currentPayment.value = null
        }
      }, 30000)
    }
  }

  // 获取当前支付
  getCurrentPayment() {
    return this.currentPayment
  }

  // 订阅支付状态更新
  subscribe(callback: (payment: PaymentInfo) => void) {
    const id = Math.random().toString(36).substr(2)
    this.callbacks.set(id, callback)

    // 返回取消订阅函数
    return () => {
      this.callbacks.delete(id)
    }
  }
}

// 导出单例
export default new PaymentService()
